package com.qf.mao.service;

import com.qf.mao.dao.UserDao;
import com.qf.mao.entity.User;
import com.qf.mao.utils.CommonsUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;

/**
 * @author 啾咪小魔王
 * @date 2022/4/6 10:24
 * @since JDK 1.8
 */
@SuppressWarnings("all")
public class UserService {
    UserDao userDao =new UserDao();
    //登录验证
    public Integer login(String username, String password, HttpServletRequest request){
        try {
            String vcode = request.getParameter("vcode");
            HttpSession session = request.getSession();
            String sessionVcode = (String) session.getAttribute("vcode");
            if (vcode == null || !vcode.equalsIgnoreCase(sessionVcode)) {
                //说明用户传递的验证码不正确
                return CommonsUtils.ERROR_SECURITY_CODE;
            }
            User user = userDao.getUserByName(username);
            if (user == null) {
                //用户名不存在
                return CommonsUtils.ERROR_USER;
            }else {
                //用户存在
                if (!user.getEnabled()) {
                    //账户禁用
                    return  CommonsUtils.ERROR_FORBIDDEN;
                }else {
                    //账户没有被禁用，校验
                    if(password.equals(user.getPassword())){
                        //成功登录
                        session.setAttribute("loginUser", user);
                        return CommonsUtils.SUCCESS_OK;
                    }else {
                        //密码错误
                        return CommonsUtils.ERROR_PASSWORD;
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return CommonsUtils.ERROR_ELSE;
    }
}
